from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend
import base64
import json


def get_private_key():
    with open('ca.key', 'rb') as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )
    return private_key


def main():
    # Load the certificate
    with open('ca.crt', 'rb') as cert_file:
        cert = load_pem_x509_certificate(cert_file.read(), default_backend())

    # Define the license part
    license_part = {
        "licenseId": "FV8EM46DQYC5AW9",
        "licenseeName": "Mr Yao",
        "licenseeType": "PERSONAL",
        "assigneeName": "",
        "assigneeEmail": "",
        "licenseRestriction": "",
        "checkConcurrentUse": False,
        "products": [
            {
                "code": "PCWMP",
                "fallbackDate": "2026-09-14",
                "paidUpTo": "2026-09-14",
                "extended": True
            },
            {
                "code": "PRR",
                "fallbackDate": "2026-09-14",
                "paidUpTo": "2026-09-14",
                "extended": True
            },
            {
                "code": "PDB",
                "fallbackDate": "2026-09-14",
                "paidUpTo": "2026-09-14",
                "extended": True
            },
            {
                "code": "PSI",
                "fallbackDate": "2026-09-14",
                "paidUpTo": "2026-09-14",
                "extended": True
            },
            {
                "code": "II",
                "fallbackDate": "2026-09-14",
                "paidUpTo": "2026-09-14",
                "extended": True
            }
        ],
        "metadata": "0220240702PSAX000005X",
        "hash": "12345678/0-541816629",
        "gracePeriodDays": 7,
        "autoProlongated": False,
        "isAutoProlongated": False,
        "trial": False,
        "aiAllowed": False
    }
    license_id = "FV8EM46DQYC5AW9"

    # Convert the license part to JSON and then to base64
    license_part_json = json.dumps(license_part).encode('utf-8')
    license_part_base64 = base64.b64encode(license_part_json).decode('utf-8')

    # Get the private key
    private_key = get_private_key()

    # Sign the license part
    signature = private_key.sign(
        license_part_json,
        padding.PKCS1v15(),
        hashes.SHA1()
    )
    signature_base64 = base64.b64encode(signature).decode('utf-8')

    # Combine results as needed
    result = f"{license_id}-{license_part_base64}-{signature_base64}-{base64.b64encode(cert.public_bytes(serialization.Encoding.DER)).decode('utf-8')}"
    print(result)


if __name__ == "__main__":
    main()